import time
from itsdangerous import BadSignature, SignatureExpired
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

# 密钥，可随意修改

# 生成token, 有效时间为600min
def generate_auth_token(user_id, expiration=300):
    # 第一个参数是内部私钥
    # 第二个参数是有效期（秒）
    SECRET_KEY = 'abcdefghijklmm'
    s = Serializer(SECRET_KEY, expires_in=expiration)
    return s.dumps({'user_id': user_id})


# 解析token
def verify_auth_token(token):
    SECRET_KEY = 'abcdefghijklmm'
    s = Serializer(SECRET_KEY)
    # token正确
    try:
        data = s.loads(token)
        return data
    # token过期
    except SignatureExpired:
        print("token 过期")
        return None
    # token错误
    except BadSignature:
        print("密钥 错误")
        return None


if __name__ == "__main__":
    user_id = "koujw0106"
    my_token = generate_auth_token(user_id)
    print("my_token ======>>> ", my_token)

    time.sleep(2)

    pares = verify_auth_token(my_token)
    print("my_token ======>>> ", pares)
    